/**
 * 全站权限配置
 *
 */
import router from '@/router'
import store from '@/store'
import i18n from './util/i18n';
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import {getUser} from '@/api/user'
import concat from 'lodash/concat'
NProgress.configure({showSpinner: false})
router.beforeEach((to, from, next) => {
    // 缓冲设置
    NProgress.start()
    //版本控制1.0
    document.title=i18n.t(to.meta.title)
    const Authorization=store.getters.userInfo.authorization
    if (Authorization) {
        if(!store.getters.userList.length){
            getUser({cache:1}).then(res=>{
                const messageList={};
                const socketInfo=res.data.socketInfo
                const userList=res.data.userList;
                concat([`groupChat_${store.getters.userInfo.username}`],res.data.userList).map(username=>{
                    if(socketInfo[username] && (store.getters.socketInfo[username] || {}).unreadCount!==socketInfo[username].unreadCount){
                        store.commit('user/SET_SOCKET_INFO',socketInfo[username])
                    }
                    messageList[username]=[]
                });
                const userSocketList=res.data.socketList
                store.commit('exclude/SET_USER_LIST',userList)
                store.commit('exclude/SET_MESSAGE_LIST',messageList)
                store.commit('exclude/SET_SOCKET_LIST',userSocketList)
                if(to.path.includes('/login')){
                    next('/')
                }else {
                    next()
                }
            })
        }else {
            if(to.path.includes('/login')){
                next('/')
            }else {
                next()
            }
        }
    } else {
        if(to.path.includes('/login')){
            next()
        }else {
            next('/login')
        }
        window.localStorage.clear()
        window.sessionStorage.clear()
    }
})

router.afterEach(() => {
    NProgress.done()
})
